package com.baidu.disk.utils;

/**
 * Created by CJ on 2018-02-28.
 */
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class PCSUploadDemo {

    //post请求地址
    private final static String API = "https://c3.pcs.baidu.com/rest/2.0/pcs/superfile2?method=upload&app_id=250528&channel=chunlei&clienttype=0&web=1&BDUSS=pansec_DCb740ccc5511e5e8fedcff06b081203-h7g1%2BrVtZr53tjCP6F6NWHYEj8nZZ5TFvjS1XPM9FpPlQiMOkopS3K09tqijQPls%2FPHY8vXSJVBr373pAS4zNcAU3k%2BerwVshTJMug%2BwcRhaIcCajunbTGU9JleUiNCKkkl7k38ZSUC4YWWS9qVPspUxHl4Mcj5oglsIQJSjZR17ZHaQEjDCKfHbv7ViBBTssCzKwC05%2BVrnaENltBxLtswDiRCdvB1y88YgJaHhDLbptzfDeW8iFsKilmi0Elna03i%2BxySns6C%2Bo5SCYMmGMw%3D%3D&logid=MTUxOTg3MzA1OTA1MDAuNTE5OTgyMzM4Njg1NDQwNQ==&path=%2F2017.12%2F%E6%96%B0%E5%BB%BA%E6%96%87%E4%BB%B6%E5%A4%B9%E5%AF%B9%E5%AF%B9%E5%AF%B9%2F1.jpg&uploadid=N1-MjIwLjI0OC41OC4xMTQ6MTUxOTg3MjQxMzoxMzc4Nzk1NTUyMTg4NjE0NzE0&uploadsign=0&partseq=0";

    //本地文件路径, 例如:"/Users/macuser/Documents/workspace/test.jpg"
    private static String mLocalPath  = "F://1.jpg";

    //上传文件路径（含上传的文件名称), 例如:"/apps/yuantest/test.jpg"
    private static String mDestPath = "/apps/yuantest/mock数据配置(1).rar";

    //开发者准入标识 access_token, 通过OAuth获得
    private static String mAccessToken = "23.418ca40608a5f8335c43b77ede4542fb.2592000.1522415933.4216709222-1641135";

    public static void main(String[] args) {


        File fileToUpload = new File(mLocalPath);
        if (!(fileToUpload).isFile()) {
            System.out.println("Input file_to_upload is invalid!");
            return;
        }

        System.out.println("Uploading...");

        Thread workerThread = new Thread(new Runnable() {
            public void run() {
                try {
                    doUpload();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        workerThread.start();

        return ;
    }

    public static void doUpload() throws IOException{
        File fileToUpload = new File(mLocalPath);

        if(null != fileToUpload && fileToUpload.length() > 0){

            ArrayList params = new ArrayList();
            params.add(new BasicNameValuePair("method", "upload"));
            params.add(new BasicNameValuePair("access_token", mAccessToken));
            params.add(new BasicNameValuePair("path", mDestPath));

            //添加请求参数，通过POST表单进行传递，除上传文件内容之外的其它参数通过query_string进行传递。
//            String postUrl = API + "?" + buildParams(params);
            String postUrl = API;
            HttpPost post = new HttpPost(postUrl);

            //添加文件内容，必须使用multipart/form-data编码的HTTP entity
            MultipartEntity entity = new MultipartEntity();
            FileBody fo = new FileBody(fileToUpload);
            entity.addPart("Filedata",fo);
            post.setEntity(entity);

            //创建client
            HttpClient client = new DefaultHttpClient();

            //发送请求
            HttpResponse response = client.execute(post);

            System.out.println(response.getStatusLine().toString());
            System.out.println(EntityUtils.toString(response.getEntity()));

        }
    }

    // url encoded query string
    protected static String buildParams(List urlParams){
        String ret = null;
        if(null != urlParams && urlParams.size() > 0){
            try {
                // 指定HTTP.UTF_8为charset参数以保证中文文件路径的正确
                HttpEntity paramsEntity = new UrlEncodedFormEntity(urlParams, HTTP.UTF_8);
                ret = EntityUtils.toString(paramsEntity);
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }




}
